package com.ys.service.base.impl;

import com.ys.entity.base.*;
import com.ys.mapper.base.TbUserPaySlipMapper;
import com.ys.mapper.base.TbUserPersonalTaxCountMapper;
import com.ys.service.base.TbUserPersonalTaxCountService;
import com.ys.util.CheckUtil;
import com.ys.util.DateUtil;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;


/**
 * 员工个税统计表
 */
@Service("tbUserPersonalTaxCountService")
public class TbUserPersonalTaxCountServiceImpl implements TbUserPersonalTaxCountService {
	private static final Logger logger = LoggerFactory.getLogger(TbUserPersonalTaxCountServiceImpl.class);

	@Autowired
	private TbUserPersonalTaxCountMapper tbUserPersonalTaxCountMapper;

	@Autowired
	private TbUserPaySlipMapper tbUserPaySlipMapper;

	/**
	 * 新增，通过员工工资表id
	 */
	@Override
	public TbUserPersonalTaxCount add(Long paySlipId)throws Exception {
		TbUserPersonalTaxCount hasAdd = new TbUserPersonalTaxCount().setPaySlipId(paySlipId).queryFirst();
		//是否新增过
		if(hasAdd!=null){
			return hasAdd;
		}
		TbUserPaySlip tbUserPaySlip = new TbUserPaySlip().setId(paySlipId).queryFirst();
		if(tbUserPaySlip!=null){
			TbUserPersonalTaxCount tbUserPersonalTaxCount = countTaxCount(new TbUserPersonalTaxCount(),tbUserPaySlip);

			//新增
			tbUserPersonalTaxCountMapper.insert(tbUserPersonalTaxCount);
			return tbUserPersonalTaxCount;
		}else{
			return null;
		}

	}


	//计算个税统计表信息
	public TbUserPersonalTaxCount countTaxCount(TbUserPersonalTaxCount tbUserPersonalTaxCount,TbUserPaySlip tbUserPaySlip)throws Exception{
		tbUserPersonalTaxCount.setCountMonth(tbUserPaySlip.getPointMonth());//统计月份
		tbUserPersonalTaxCount.setUserId(tbUserPaySlip.getUserId());//员工工号
		tbUserPersonalTaxCount.setPaySlipId(tbUserPaySlip.getId());//员工工资表id
		tbUserPersonalTaxCount.setOrgId(tbUserPaySlip.getOrgId());//组织机构id

		//收入
		tbUserPersonalTaxCount.setIncome(tbUserPaySlip.getTaxPaySlip());


		String[] dateArr = tbUserPaySlip.getPointMonth().split("-");
		//*****旧：计算：扣除费用 = 个税征收标准*（统计月份+1）
			/*
			String[] dateArr = tbUserPaySlip.getPointMonth().split("-");
			BigDecimal monthNum = new BigDecimal(dateArr[1]).add(BigDecimal.ONE);
			BigDecimal deductCost = taxLevyCriterion.multiply(monthNum);
			 */
		//新：扣除费用 = 5000
		tbUserPersonalTaxCount.setDeductCost(new BigDecimal(5000));//扣除费用

		//*****计算：专项扣除 = 养老保险（个人）+失业保险（个人）+医疗保险（个人）+公积金（个人）
		BigDecimal specialDeductCost = (tbUserPaySlip.getRetirementPersonal()//养老保险（个人）
				.add(tbUserPaySlip.getLoseWorkPersonal())//失业保险（个人）
				.add(tbUserPaySlip.getHealthPersonal())//医疗保险（个人）
				.add(tbUserPaySlip.getAccumulationFundPersonal()))//公积金（个人）
				.setScale(2, BigDecimal.ROUND_HALF_UP);
		tbUserPersonalTaxCount.setSpecialDeductCost(specialDeductCost);

		//其他扣除
		tbUserPersonalTaxCount.setOtherDeductCost(BigDecimal.ZERO);

		//专项附加扣除
		TbUserTaxManageItem tbUserTaxManageItem = new TbUserTaxManageItem().setUserId(tbUserPaySlip.getUserId()).queryFirst();
		BigDecimal specialAddDeductCost = BigDecimal.ZERO;
		if(tbUserTaxManageItem!=null){
			specialAddDeductCost = tbUserTaxManageItem.getSpecialDeductNum();
		}
		tbUserPersonalTaxCount.setSpecialAddDeductCost(specialAddDeductCost);

		BigDecimal incomeAddupBefore = BigDecimal.ZERO;//上月收入累计
		BigDecimal deductCostAddupBefore = BigDecimal.ZERO;//上月扣除费用
		BigDecimal specialDeductCostAddupBefore = BigDecimal.ZERO;//上月专项扣除
		BigDecimal otherDeductCostAddupBefore = BigDecimal.ZERO;//上月其他扣除
		BigDecimal specialAddDeductCostAddupBefore = BigDecimal.ZERO;//上月专项附加扣除
		BigDecimal yearAddupTaxBefore = BigDecimal.ZERO;//上月本年累计税额
		BigDecimal submitAddupTaxBefore = BigDecimal.ZERO;//上月累计已交税额
		//获取上个月日期信息
		if(Integer.parseInt(dateArr[1])!=12){//12月份、或者用户公司切换时=》重新计算累计
			//int beforeMonth = Integer.parseInt(dateArr[1])-1;
			//String beforeMonthStr = beforeMonth<10?"0"+beforeMonth:beforeMonth+"";
			//String oldMonth = dateArr[0]+"-"+ beforeMonthStr;
			String oldMonth = DateUtil.getYYYY_MM(DateUtil.addMonth(tbUserPaySlip.getPointMonth(),-1));
			tbUserPersonalTaxCount.setCountMonthBefore(oldMonth);//上个月日期信息
			TbUserPersonalTaxCount tbUserPersonalTaxCountBefore = new TbUserPersonalTaxCount()
					.setUserId(tbUserPaySlip.getUserId())
					.setCountMonth(oldMonth)
					.queryFirst();
			//用户公司切换时=》重新计算累计
			//未切换则累计叠加
			if(tbUserPersonalTaxCountBefore!=null && tbUserPersonalTaxCountBefore.getOrgId().equals(tbUserPersonalTaxCount.getOrgId())){
				incomeAddupBefore = tbUserPersonalTaxCountBefore.getIncomeAddup();
				deductCostAddupBefore = tbUserPersonalTaxCountBefore.getDeductCostAddup();
				specialDeductCostAddupBefore = tbUserPersonalTaxCountBefore.getSpecialDeductCostAddup();
				otherDeductCostAddupBefore = tbUserPersonalTaxCountBefore.getOtherDeductCostAddup();
				specialAddDeductCostAddupBefore = tbUserPersonalTaxCountBefore.getSpecialAddDeductCostAddup();
				yearAddupTaxBefore = tbUserPersonalTaxCountBefore.getYearAddupTax();
				submitAddupTaxBefore = tbUserPersonalTaxCountBefore.getSubmitAddupTax();
			}else{
				//若是新入职员工，上个月无数据，则默认上个月已累计 5000
				if(tbUserPersonalTaxCountBefore == null || tbUserPersonalTaxCountBefore.getId()==null){
					deductCostAddupBefore = new BigDecimal(5000);
				}

			}
		}

		//收入累计
		BigDecimal incomeAddup = (tbUserPersonalTaxCount.getIncome().add(incomeAddupBefore)).setScale(2, BigDecimal.ROUND_HALF_UP);
		tbUserPersonalTaxCount.setIncomeAddup(incomeAddup);
		//扣除费用累计
		BigDecimal deductCostAddup = (tbUserPersonalTaxCount.getDeductCost().add(deductCostAddupBefore)).setScale(2, BigDecimal.ROUND_HALF_UP);
		tbUserPersonalTaxCount.setDeductCostAddup(deductCostAddup);
		//专项扣除累计
		BigDecimal specialDeductCostAddup = (tbUserPersonalTaxCount.getSpecialDeductCost().add(specialDeductCostAddupBefore)).setScale(2, BigDecimal.ROUND_HALF_UP);
		tbUserPersonalTaxCount.setSpecialDeductCostAddup(specialDeductCostAddup);
		//其他扣除累计
		BigDecimal otherDeductCostAddup = (tbUserPersonalTaxCount.getOtherDeductCost().add(otherDeductCostAddupBefore)).setScale(2, BigDecimal.ROUND_HALF_UP);
		tbUserPersonalTaxCount.setOtherDeductCostAddup(otherDeductCostAddup);
		//专项附加扣除累计
		BigDecimal specialAddDeductCostAddup = (tbUserPersonalTaxCount.getSpecialAddDeductCost().add(specialAddDeductCostAddupBefore)).setScale(2, BigDecimal.ROUND_HALF_UP);
		tbUserPersonalTaxCount.setSpecialAddDeductCostAddup(specialAddDeductCostAddup);

		//旧：应纳税所得额 = （本月累计收入-本月累计减除费用-本月累计其他扣除-本月累计专项扣除）
		//新：应纳税所得额 = （本月累计收入-本月累计减除费用-本月累计其他扣除-本月累计专项扣除-本月累计专项附加扣除）
		BigDecimal needPayGetTax = (incomeAddup//本月累计收入
				.subtract(deductCostAddup)//本月累计减除费用
				.subtract(specialDeductCostAddup)//本月累计专项扣除
				.subtract(otherDeductCostAddup)//本月累计其他扣除
				.subtract(specialAddDeductCostAddup)//本月累计专项附加扣除
		).setScale(2, BigDecimal.ROUND_HALF_UP);
		//如果小于0，则改为0
		if(needPayGetTax.compareTo(BigDecimal.ZERO)<0){
			needPayGetTax = BigDecimal.ZERO;
		}
		tbUserPersonalTaxCount.setNeedPayGetTax(needPayGetTax);

		//本年累计税额 = 应纳税所得额*档位对应税率（员工个税管理）-档位对应速算扣除数
		BigDecimal taxRate = BigDecimal.ZERO;
		BigDecimal deductNum = BigDecimal.ZERO;
		TbUserTaxRate tbUserTaxRate = new TbUserTaxRate()
				.where("A.YearTaxMin <" + needPayGetTax)
				.where("A.YearTaxMax >=" + needPayGetTax)
				.queryFirst();
		if(tbUserTaxRate!=null){
			taxRate = tbUserTaxRate.getTaxRate().divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);//保留2位小数，四舍五入
			deductNum = tbUserTaxRate.getDeductNum();
		}
		BigDecimal yearAddupTax = (needPayGetTax.multiply(taxRate).subtract(deductNum)).setScale(2, BigDecimal.ROUND_HALF_UP);
		tbUserPersonalTaxCount.setYearAddupTax(yearAddupTax);

		//旧：累计已交税额 = 上个月的本年累计税额
		//新：MAX(上个月的本年累计税额，上月本年累计已交税额) =》二者取大值
		if(submitAddupTaxBefore.compareTo(yearAddupTaxBefore)>0){
			tbUserPersonalTaxCount.setSubmitAddupTax(submitAddupTaxBefore);
		}else {
			tbUserPersonalTaxCount.setSubmitAddupTax(yearAddupTaxBefore);
		}
		//本月应纳税额 = 本年累计税额-累计已交税额
		tbUserPersonalTaxCount.setMonthNeedPayTax((yearAddupTax.subtract(tbUserPersonalTaxCount.getSubmitAddupTax())).setScale(2, BigDecimal.ROUND_HALF_UP));
		//如果小于0，则改为0
		if(tbUserPersonalTaxCount.getMonthNeedPayTax().compareTo(BigDecimal.ZERO)<0){
			tbUserPersonalTaxCount.setMonthNeedPayTax(BigDecimal.ZERO);
		}

		//状态
		tbUserPersonalTaxCount.setStatus(1);

		return tbUserPersonalTaxCount;
	}

	/**
	 * 删除
	 */
	@Override
	public R toDel(Long id)throws Exception{
		TbUserPersonalTaxCount tbUserPersonalTaxCount = new TbUserPersonalTaxCount().setId(id).queryFirst();
		if(tbUserPersonalTaxCount!=null){
			//工资表工资状态为"已导入"才可以删除
			int paySlipStatusIsNull = new TbUserPaySlip().setId(tbUserPersonalTaxCount.getPaySlipId()).setSlipStatus(1).count();
			if(paySlipStatusIsNull>0){
				TbUserPaySlip tbUserPaySlip = new TbUserPaySlip();
				tbUserPaySlip.setId(tbUserPersonalTaxCount.getPaySlipId());
				tbUserPaySlip.setSlipStatus(0);//删除后，工资条中，工资状态变为“空”
				tbUserPaySlipMapper.update(tbUserPaySlip);
				tbUserPersonalTaxCountMapper.deleteTrue(id);
			}else {
				return R.error();
			}
		}else{
			return R.error();
		}
		return R.ok();
	}




	/**
	 * 手动刷新统计信息
	 */
	@Override
	public TbUserPersonalTaxCount updateBySouDong(Long paySlipId)throws Exception {
		logger.info("***********开始:"+paySlipId+"***********");
		/*
		TbUserPersonalTaxCount hasAdd = new TbUserPersonalTaxCount().setPaySlipId(paySlipId).queryFirst();
		//是否新增过
		if(hasAdd!=null){
			return hasAdd;
		}
		 */
		TbUserPaySlip tbUserPaySlip = new TbUserPaySlip().setId(paySlipId).queryFirst();
		if(tbUserPaySlip==null){
			return null;
		}
		TbUserPersonalTaxCount tbUserPersonalTaxCount = new TbUserPersonalTaxCount().setPaySlipId(paySlipId).queryFirst();
		if(tbUserPersonalTaxCount!=null){
			//logger.info("***********获取:"+paySlipId+"***********");
			tbUserPersonalTaxCount = countTaxCount(tbUserPersonalTaxCount,tbUserPaySlip);
			//编辑
			tbUserPersonalTaxCountMapper.update(tbUserPersonalTaxCount);
			return tbUserPersonalTaxCount;
		}else{
			return null;
		}

	}



}
